#!/usr/bin/env bash

#### crowsnest - A webcam Service for multiple Cams and Stream Services.
####
#### Written by Stephan Wendel aka KwadFan <me@stephanwe.de>
#### Copyright 2021
#### https://github.com/mainsail-crew/crowsnest
####
#### This File is distributed under GPLv3
####

# shellcheck enable=requires-variable-braces

# Error handling
set -Ee

# shellcheck disable=SC1091
source /common.sh
install_cleanup_trap

# Module only Variables
CN_BUILD_PACKAGE_FILE="/tmp/cn_packages.lst"

# Helper Func
is_raspbian() {
    if [[ -f /boot/config.txt ]] && [[ -f /etc/rpi-issue ]]; then
        echo "1"
    else
        echo "0"
    fi
}

get_pkglist() {
    if [[ "$(is_raspbian)" = "1" ]]; then
        CN_BUILD_INSTALL_SH="/home/${BASE_USER}/crowsnest/tools/libs/pkglist-rpi.sh"
    fi
    if [[ "$(is_raspbian)" = "0" ]]; then
        CN_BUILD_INSTALL_SH="/home/${BASE_USER}/crowsnest/tools/libs/pkglist-generic.sh"
    fi
}


echo_green "Installing crowsnest ..."

## Force apt update
apt-get update
## Make sure 'git' is installed!
check_install_pkgs git

## Step 1: Move to Home Dir as WorkingDirectoy
pushd "/home/${BASE_USER}" &> /dev/null || exit 1

## Step 2: clone crowsnest repo
echo_green "Clone crowsnest repository ..."
gitclone CROWSNEST_REPO crowsnest

## Step 3: grep PKGLIST from install.sh for dependencies
echo_green "Generating packages file ..."
get_pkglist
grep "PKGLIST=" "${CN_BUILD_INSTALL_SH}" >> "${CN_BUILD_PACKAGE_FILE}"

## Step 4: Rename PKGLIST to Module usable Var
echo_green "Rename variable PKGLIST to CROWSNEST_DEPS ..."
sed -i 's/PKGLIST/CROWSNEST_DEPS/g' "${CN_BUILD_PACKAGE_FILE}"

## Step 5: Source cn_package.lst file
# shellcheck disable=SC1090
# Shellcheck has to be disabled here,
# because it is an dynamic generated file and not checkable
. "${CN_BUILD_PACKAGE_FILE}"

## Step 6: Install packages
echo_green "Install crowsnest dependencies ..."
# shellcheck disable=SC2086
# disabled because we need 'wordsplitting'
check_install_pkgs ${CROWSNEST_DEPS}

## Step 7: Move to crowsnest as working directory
pushd "/home/${BASE_USER}/crowsnest" &> /dev/null || exit 1

## Step 8: Run crowsnest install routine
echo_green "Launch crowsnest install routine ..."
make install

## Step 9: Leave crowsnest
popd &> /dev/null || exit 1

## Step 10: clean packages.lst file
rm -f "${CN_BUILD_PACKAGE_FILE}"

## Step 11: leave home dir
popd &> /dev/null || exit 1

## Step 12:
echo_green "Enable crowsnest.service ..."
systemctl_if_exists enable crowsnest.service

## Finish
echo_green "Installing crowsnest ... DONE!"
